/*
 * Copyright 2011-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.framework.test.thread;

/**
 * 一个展示 Thread.stop() 方法为什么被弃用的例子
 *
 * @author liym
 * @since 2020-01-10 17:32 新建
 */
public final class ThreadStopDemo {

    private ThreadStopDemo() {}

    public static void main(String[] args) {
        StopThread thread = new StopThread();
        thread.start();
        try {
            //休眠1秒，确保i变量自增成功
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            //一般会处理中断异常，这里作为例子就直接打印到控制台了
            e.printStackTrace();
        }
        //暂停线程
        thread.stop();

        //确保线程已经终止
        while (thread.isAlive()) {
        }
        //输出结果
        thread.print();
    }

    /**
     * 展示用的例子，内部对两个整数做自增
     *
     * @author RJH
     * @date 2017年12月11日 下午7:48:32
     */
    private static class StopThread extends Thread {

        private int i = 0;
        private int j = 0;

        @Override
        public void run() {
            // 使用同步锁，确保线程安全
            synchronized (this) {
                ++this.i;
                try {
                    // 休眠10秒，模拟耗时操作
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ++this.j;
            }
        }

        /**
         * 打印 i、j
         */
        public void print() {
            System.out.println("i=" + this.i + ", j=" + this.j);
        }

    }

}
